package net.form.processing;

import java.awt.Color;

public class Rotate extends AbstractImageCommand {

	private int angle;
	private static int black = (new Color(0, 0, 0)).getRGB();
	
	public Rotate(Image image,int angle) {
		super(image);
		this.angle=angle;
	}
	
	public Image execute() {
		return RotateImage(image,angle);
	}

	public static Image RotateImage(Image originalImage, double angle) {
		// convert the angle to radians
		angle = angle * Math.PI / 180;
		// calculate the cosine and sine of the angle
		double cosine = Math.cos(angle);
		double sine = Math.sin(angle);
		// dimensions of the original image
		int originalWidthSize=originalImage.getWidth();
		int originalHeightSize=originalImage.getHeight();
		// calculate the dimensions of the result image 
		int resultWidthSize  = (int) Math.round( Math.abs(originalWidthSize * sine   ) + Math.abs(originalHeightSize * cosine ));
		int resultHeightSize = (int) Math.round( Math.abs(originalWidthSize * cosine ) + Math.abs(originalHeightSize * sine ));
		// image result
		Image resultImage = new Image(resultWidthSize,resultHeightSize);
		// point to rotate about center of image
		int x0Result=resultWidthSize/2;
		int y0Result=resultHeightSize/2;
		int x0Original=originalWidthSize/2;
		int y0Original=originalHeightSize/2;
		// rotation
		for (int x = 0; x < resultWidthSize; x++)
			for (int y = 0; y < resultHeightSize; y++) {
				int i=(int) Math.round((((x-x0Result) * cosine) - ((y-y0Result) * sine)))   + (x0Original);
				int j=(int) Math.round((((x-x0Result) * sine )  + ((y-y0Result) * cosine))) + (y0Original);
				if (i >= 0 && i < originalWidthSize
						&& j < originalHeightSize && j >= 0)
					resultImage.setRGB(x, y, originalImage.getRGB(i, j));
				else
					resultImage.setRGB(x, y, black);
			}
		return resultImage;
	}
	
	public String getCommandName() {
		return null;
	}

}
